package tool.zyk.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;
import tool.zyk.configuration.SimpleRpcConfiguration;
import tool.zyk.consts.SerializableTypeEnum;
import tool.zyk.serializable.SerializableFactory;
import tool.zyk.stardand.RpcProtocol;
import tool.zyk.stardand.RpcRequest;
import tool.zyk.utils.LogUtil;

import java.util.List;

/**
 * author: zyk
 * datetime: 2024/1/29 21:06
 * describe:
 */
@Slf4j
public class ProtocolRequestM2MEncoder extends MessageToMessageEncoder<RpcRequest> {
    private final SimpleRpcConfiguration simpleRpcConfiguration;

    public ProtocolRequestM2MEncoder(SimpleRpcConfiguration simpleRpcConfiguration) {
        this.simpleRpcConfiguration = simpleRpcConfiguration;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcRequest msg, List<Object> out) throws Exception {
        try {
            log.debug("request encode->收到请求信息:{}", msg);
            SerializableTypeEnum serializableType = simpleRpcConfiguration.getSerializableType();
            //获取序列化后的应用层面的数据
            byte[] dataByte = SerializableFactory.getSerializableConverter(serializableType).parseTransferData2Object(msg);
            RpcProtocol rpcProtocol = RpcProtocol.ofRequest(dataByte, serializableType);
            out.add(rpcProtocol);
        } catch (Throwable throwable) {
            LogUtil.printErrorLog(throwable);
            throw new RuntimeException(throwable);
        }
    }
}
